package com.example.base.mvi

import android.content.Intent
import android.content.SyncRequest
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.base.entity.Res
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch

abstract class BaseViewModel<UiIntent : IUiIntent>:ViewModel() {
    val channel = Channel<UiIntent>()

    private var _state = MutableStateFlow<UiState>(UiState.onLoading)

    val uiState:StateFlow<UiState>
        get() = _state.asStateFlow()

    init {
        viewModelScope.launch {
            channel.receiveAsFlow().collect{
                handlerIntent(it)
            }
        }
    }

    //处理意图
    abstract fun handlerIntent(it :UiIntent)

    fun sendIntent(intent: UiIntent){
        viewModelScope.launch {
            channel.send(intent)
        }
    }

    fun<T> httpRequest(request: Flow<Res<T>>){
        viewModelScope.launch {
                request.flowOn(Dispatchers.IO)
                    .catch {
                        Log.i("xs", it.message.toString())
                    }.collect {
                        if (it.code == 200) {
                            _state.value = UiState.onSuccess(it.data)
                        } else {
                            _state.value = UiState.onError(it.message)
                        }
                    }
        }
    }
}